package com.naiterui.ehp.bs.weixin.security.util;

import com.naiterui.ehp.bs.weixin.exception.WeixinCode;
import com.naiterui.ehp.bs.weixin.exception.WeixinException;
import com.naiterui.ehp.bs.weixin.security.bean.JwtUser;
import java.util.Optional;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 用户工具类
 */
public class JwtUserUtil {

    /**
     * 获取当前的用户
     */
    public static JwtUser getJwtUser() throws WeixinException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new WeixinException(WeixinCode.WECHAT_LOGIN_FAIL);
        }
        return (JwtUser) authentication.getPrincipal();
    }

    /**
     * 获取当前的用户,无用户则表示未授权，不阻塞业务
     */
    public static JwtUser getJwtUserNullable() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        JwtUser jwtUser = (JwtUser) Optional.ofNullable(authentication).map(Authentication::getPrincipal).orElse(null);
        return jwtUser;
    }

}
